package com.firewolf.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

/**
 * 作者：刘兴
 * 时间:18/12/2
 **/
public class CustomRealmWithSalt extends AuthorizingRealm {


    @Override
    public String getName() {
        return "这是我的自定义Realm"; //重写方法，更改自定义Realm的名字
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String userName = (String) principals.getPrimaryPrincipal();
        //从数据库或者缓存中获取角色和权限数据
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("user");

        //权限数据
        Set<String> permissions = new HashSet<>();
        permissions.add("user:delete");
        permissions.add("user:add");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String userName = (String) token.getPrincipal();

        //这里的密码是加盐之后的密码
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("zhang", "d4f37ba0ac6672f7030e178079d72315", getName());
        //设置盐值，这个盐值，我们一般是在存储密码的时候，使用UUID生成的，存储在数据库的，
        //当然，也可以使用用户名等，也可以是写死的一个盐，这里我写死一个"1111"
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("1111"));
        return authenticationInfo;
    }


    public static void main(String[] args) {
        //存储到数据的的时候，使用的如下方式加密后存储的，而不是存储的明文
        Md5Hash md5Hash = new Md5Hash("123","1111");
        String s = md5Hash.toString();
        System.out.println(s);

    }
}
